const Mongoose = require('mongoose')

const WechatUserSchema = new Mongoose.Schema({
    openid: String,
    sessionWechat: String,
    session3rd: String,
    expiresIn: Number,
})

WechatUserSchema.index({ openid: 1 }, { unique: true });

WechatUserSchema.statics.get = function (openid, callback) {
    this.findOne({openid: openid}, callback)
}

WechatUserSchema.statics.set = function (openid, session_wechat, callback) {
    this.findOneAndUpdate(
        { openid: openid },                  // conditions
        { sessionWechat: session_wechat },   // doc
        { upsert: true },                    // options
        callback
    )
}

WechatUserSchema.statics.initSession = function (openid, callback) {
    const randomId = Mongoose.Types.ObjectId();
    let expires = new Date();
    expires.setDate(expires.getDate() + 10);

    this.findOneAndUpdate(
        { openid: openid },
        {
            session3rd: randomId.toHexString(),
            expiresIn: expires.getTime()
        },
        { upsert: false },
        callback
    )
}

WechatUserSchema.statics.getBySession = function (session, callback) {
    this.findOne({session3rd: session}, function (err, result) {
        if (err) throw err
        if (!result) return callback(null, result)
        let now = new Date()
        if (result.expiresIn < now.getTime()) // checkSessionExpires
            return callback({expires: true})
        return callback(null, result)
    })
}

const WechatUser = Mongoose.model('WechatUser', WechatUserSchema)

module.exports = WechatUser;